$import("biz.base.CompositePanel"); 

function getUserMenuMacePanel(region){
	var clrMap={"0":"#000","1":"#000","2":"#0f0","-1":"#f00"};
	function checkMace(treePanel, data) {
		var rootNode = treePanel.getRootNode();
		loadCheck(rootNode, data);
	}

	function loadCheck(node, maceIds) {//
		var attrs = node.attributes;
		if (!node.attributes.raw)
			node.attributes.raw = attrs["text"];
		var checked = existInArray(attrs["id"], maceIds);
		var a = node.ui.checkbox;
		if (a) {
			a.checked = checked;
			attrs.checked = checked;
			var old = node.attributes["state"];
			node.attributes["state"] = checked ? 1 : 0;// 默认选中
			if (old) {
				node.setText("<font color='" + clrMap[attrs["state"] + ""] + "'>"
						+ node.attributes.raw + "</font>");
			} else {
				node.setText("<font color='" + clrMap[attrs["state"] + ""] + "'>"
						+ node.attributes.raw + "</font>");
			}
		}
		node.expand();
		node.eachChild(function(child) {
			loadCheck(child, maceIds);
		});
	}

	function expandTree(tree){
		var rootNode=tree.getRootNode();
		expandNode(rootNode);
	}
	function expandNode(node){
		node.expand();
		node.eachChild(function(child) {
			expandNode(child);
		});
	}

	function existInArray(id,ids){
		for(var i in ids){
			if(id==ids[i])
				return true;
		}
		return false;
	}
	function collectMod(node, o) {// 收集用户所做的修改
		var attrs = node.attributes;
		switch (attrs["state"]) {
		case -1:
			var dme = o["dels"];
			dme[dme.length] = attrs["id"];
			break;
		case 2:
			var ame = o["adds"];
			ame[ame.length] = attrs["id"];
			break;
		default:
			break;
		}
		node.expand();
		node.eachChild(function(child) {
			collectMod(child, o);
		});
	}

	// state 0：默认未选，1：默认选中，2：新增，-1：删除
	function changeState(node, checked) {// 改变当前节点状态
		var attrs = node.attributes;
		var old = attrs["state"];
		if (attrs["state"] == null)
			return;
		if (checked) {
			if (attrs["state"] <= 0)
				attrs["state"] += 2;
		} else {
			if (attrs["state"] > 0)
				attrs["state"] -= 2;
		}
		if (old != attrs["state"])// change text color
			node.setText("<font color='" + clrMap[attrs["state"] + ""] + "'>"
					+ node.attributes.raw + "</font>");
	}

	function checkParent(node) {// 同步所有父节点
		var p = node.parentNode;
		if (!p)
			return;
		var a = p.ui.checkbox;
		if (node.attributes.checked) {
			if (a) {
				p.attributes.checked = true;
				a.checked = true;
				changeState(p, true);
				checkParent(p);
			}
		} else {
			var flag = true;
			p.eachChild(function(child) {
				if (child.attributes.checked) {
					flag = false;
					return;
				}
			});
			if (flag && a) {
				p.attributes.checked = false;
				a.checked = false;
				changeState(p, false);
				checkParent(p);
			}
		}
	}

	function checkChildren(node, checked) {// 同步所有子节点
		if (!node)
			return;
		node.expand();
		changeState(node, checked);
		node.eachChild(function(child) {
			var a = child.ui.checkbox;
			if (a) {
				a.checked = checked;
				child.attributes.checked = checked;
				checkChildren(child, checked);
			}
		});
	}
	var treeLoader = new Ext.tree.TreeLoader({dataUrl:'../module/Tree-getAllByUser.action',baseAttrs:{checked:false,expanded:true}});
	var checkTree= new Ext.tree.TreePanel({
        region:'west',
        id:'menuMace',
        title:'菜单权限',
        split:true,
        autoScroll: true,
        region:region,
        width: 200,
        animate: true,
        minSize: 175,
        maxSize: 400,
        expanded : true,
        collapsible: false,
        floatable: false,
        tbar:[{
			xtype : 'button',
			text : '保存',
			iconCls : 'icon-submit',
			tooltip : {
				text : '保存新增或删除的权限'
			},
			handler : function() {
				var row=Ext.getCmp('role_grid')["cur_row"];
				if (!row)
					return Ext.Msg.alert('提示','请先选择要操作的用户!');
				var o = {uid: row.get("SID"),adds: [],dels: []};
				collectMod(checkTree.getRootNode(), o);
				if (o["adds"].length == 0&& o["dels"].length == 0)
					return Ext.Msg.alert('提示','没有改动，无需提交!');
				var url = "module/Mace-saveMenuMaces.action?jsonStr=" + Ext.encode(o);
				var rs=Ext.decode(doHttpPost(getContextBase() + url).text);
				checkMace(checkTree, rs["data"]);
			}
		} ,{
			xtype : 'button',
			text : '刷新',
			iconCls : 'icon-reload',
			tooltip : {
				text : '刷新权限'
			},
			handler:function(){
				var checkTree=Ext.getCmp('menuMace');
				checkTree.getRootNode().reload();
			}}],
			listeners : {
				'checkchange' : function(node, checked) {
					
					var sels=Ext.getCmp('role_grid').selModel.getSelections();
					if (sels.length==0){
						node.ui.checkbox.checked = false;
						node.attributes.checked = false;
						return Ext.Msg.alert('提示','请先选择用户!');
					}
					checkChildren(node, checked);
					checkParent(node);
				}
			},
        titleCollapse:true,
        margins:'0 0 0 1',	
        rootVisible: false,
	       lines: false,
	       border:false,
//	       singleExpand: false,
	       useArrows: true,		       
	       loader: treeLoader,
	       root: new Ext.tree.AsyncTreeNode({id:'ccc',text:'根节点'})
           
});
	
	checkTree.on('load', function(){
		var sels=Ext.getCmp('role_grid').getSelectionModel().getSelections();
		if(sels.length==0)return;
		var row=sels[0];
		var url=getContextBase()+"module/Mace-getMacesByUid.action?uid="+row.get("SID");
		var mace=Ext.decode(doHttpPost(url).text);
		checkMace(checkTree,mace["data"]);
    });
	return checkTree;
}

function getMaceWin(){
	var maceWin=Ext.getCmp('maceWin');
	if(!maceWin){
		var userMenuMace=getUserMenuMacePanel('center');
		
		maceWin= new Ext.Window({
		      layout:'border',
		      id:'maceWin',
		      scrollable:true,
		      modal:true,
		      title:'权限分配',
		      width:800,
		      height:480,
		      plain: true,
		      items: userMenuMace
			 });
		}
	return  maceWin.show();
}

function initRolePanel(){
	var companel = new CompositePanel({
		metaCode:'BT_ROLE',
		searchFields:['SID','NAME','TEXT',"TIMS"],
		showColumns:['SID','TEXT','NAME'],
		defaultFilters:{UNID:unid,FID:unid,RANK:1008,FLAG:1}
	});
	companel.initBefore=function(){
      	this.dataConfig.idProperty="SID";
      	this.dataConfig.sortInfo={field:"SID",direction:"DESC"};
       	this.gridConfig.xtype='editorgrid';
       	this.handlers.put('doMace',{text:'权限',iconCls:'icon-finish', tooltip:{text:'权限控制',title:'权限控制'}});
        this.gridConfig.tbar=this.getButtons(['doAddNew','doModify','doDelete','splitter','doReload','doCommit','doMace']);
        this.doMace=function(){
 	   		getMaceWin();
 	   	};
 	   this.doubleClick=function(grid, rowindex, e){};
	};
   	companel.display();
     return companel.gridPanel;
}


Ext.onReady(function(){
      Ext.QuickTips.init();
      initRolePanel();
      
 });